<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>User's Guide</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">        
        <meta name="description" content="Pistache is a C++ REST framework focussed on high performance and clear API. Pistache is a free software written by Mathieu Stefani and available on Github - https://github.com/oktal/pistache
">
        <link rel="canonical" 
        href="http://localhost:4000/guide/">
        
        <!-- Harmony styles -->
        <link rel="stylesheet" type="text/css" href="/assets/css/main.css">

        <!-- Modernizr js -->
        <script async src="/assets/js/modernizr.js"></script>    

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
        <!--[if lt IE 9]>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.ie.min.css" />
        <![endif]-->

        <!-- IE Fixes -->
        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->        
    </head>
    <body class="theme-base-01">
        <header class="main-header">
            <div class="wc-container">
                <img id="img-logo" src="/assets/images/logo.png" />
                <h1>
                     <a href="/">Pistache</a>
                </h1>
                <h2>An elegant C++ REST framework.</h2>
                <ul>
    
    
		
  	
		
  	
		
            <li>
                
                  <a href="/">Pistache</a><span>/</span>
                
            </li>
	    
  	
		
  	
		
            <li>
                
                  <a href="/quickstart">Getting Started</a><span>/</span>
                
            </li>
	    
  	
		
            <li>
                
                  <a class="active" href="/guide/" class="active">User's Guide</a><span>/</span>
                
            </li>
	    
  	

	
	<li>
		<a title="Pistache on Github" 
			href="https://github.com/oktal/pistache" target="_blank">
			Source code
		</a><span>/</span>
	</li>
	
</ul>
                
                <div style="text-align: center">
                    <iframe src="https://ghbtns.com/github-btn.html?user=oktal&repo=pistache&type=star&count=true&size=large" frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
                    <iframe src="https://ghbtns.com/github-btn.html?user=oktal&repo=pistache&type=fork&count=true&size=large" frameborder="0" scrolling="0" width="158px" height="30px"></iframe>
                </div>
            </div>
        </header>
        <div class="page-content wc-container">
	<div class="post">
		<h1>User's Guide</h1>
		<div class="post">
			<ul id="markdown-toc">
  <li><a href="#namespace" id="markdown-toc-namespace">Namespace</a></li>
  <li><a href="#http-handler" id="markdown-toc-http-handler">Http Handler</a>    <ul>
      <li><a href="#sending-a-response" id="markdown-toc-sending-a-response">Sending a response</a></li>
      <li><a href="#response-streaming" id="markdown-toc-response-streaming">Response streaming</a></li>
      <li><a href="#static-file-serving" id="markdown-toc-static-file-serving">Static file serving</a></li>
      <li><a href="#controlling-timeout" id="markdown-toc-controlling-timeout">Controlling timeout</a></li>
    </ul>
  </li>
  <li><a href="#asynchronous-http-programming" id="markdown-toc-asynchronous-http-programming">Asynchronous HTTP programming</a></li>
  <li><a href="#headers" id="markdown-toc-headers">Headers</a>    <ul>
      <li><a href="#overview" id="markdown-toc-overview">Overview</a></li>
      <li><a href="#defining-your-own-header" id="markdown-toc-defining-your-own-header">Defining your own header</a></li>
      <li><a href="#mime-types" id="markdown-toc-mime-types">MIME types</a></li>
    </ul>
  </li>
  <li><a href="#routing" id="markdown-toc-routing">Routing</a>    <ul>
      <li><a href="#http-methods" id="markdown-toc-http-methods">HTTP methods</a></li>
      <li><a href="#route-patterns" id="markdown-toc-route-patterns">Route patterns</a>        <ul>
          <li><a href="#static-routes" id="markdown-toc-static-routes">Static routes</a></li>
          <li><a href="#dynamic-routes" id="markdown-toc-dynamic-routes">Dynamic routes</a></li>
        </ul>
      </li>
      <li><a href="#defining-routes" id="markdown-toc-defining-routes">Defining routes</a>        <ul>
          <li><a href="#callbacks" id="markdown-toc-callbacks">Callbacks</a></li>
        </ul>
      </li>
      <li><a href="#installing-the-handler" id="markdown-toc-installing-the-handler">Installing the handler</a></li>
    </ul>
  </li>
  <li><a href="#rest-description" id="markdown-toc-rest-description">REST description</a>    <ul>
      <li><a href="#swagger" id="markdown-toc-swagger">Swagger</a></li>
    </ul>
  </li>
  <li><a href="#api-reference" id="markdown-toc-api-reference">API Reference</a></li>
</ul>

<h1 id="namespace">Namespace</h1>

<p>Most of the components provided by <code>Pistache</code> live in the <code>Net</code> namespace. It is thus
recommended to directly import this namespace with a <code>using-declaration</code>:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">using</span> <span class="k">namespace</span> <span class="n">Net</span><span class="p">;</span></code></pre></figure>

<h1 id="http-handler">Http Handler</h1>

<p>Requests that are received by <code>Pistache</code> are handled by a special class called <code>Http::Handler</code>.
This class declares a bunch of virtual methods that can be overriden to handle special events
that occur on the socket and/or connection.</p>

<p>The <code>onRequest()</code> function <strong>must</strong> be overriden. This function is called whenever <code>Pistache</code> 
received data and correctly parsed it as an http request.</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">virtual</span> <span class="kt">void</span> <span class="nf">onRequest</span><span class="p">(</span><span class="k">const</span> <span class="n">Http</span><span class="o">::</span><span class="n">Request</span><span class="o">&amp;</span> <span class="n">request</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">ResponseWriter</span> <span class="n">response</span><span class="p">);</span></code></pre></figure>

<p>The first argument is an object of type <code>Http::Request</code> representing the request itself.
It contains a bunch of informations including:</p>

<ul>
  <li>The resource associated to the request</li>
  <li>The query parameters</li>
  <li>The headers</li>
  <li>The body of the request</li>
</ul>

<p>The <code>Request</code> object gives a <code>read-only</code> access to these informations. You can access them
through a couple of getters but can not modify them. An http request is <strong>immutable</strong>.</p>

<h2 id="sending-a-response">Sending a response</h2>

<p><code>ResponseWriter</code> is an object from which the final http response is sent to the client.
The <code>onRequest()</code>  function does not return anything (<code>void</code>). Instead, the response is
sent through the <code>ResponseWriter</code> class. This class provides a bunch of <code>send()</code> function
overloads to send the response:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Async</span><span class="o">::</span><span class="n">Promise</span><span class="o">&lt;</span><span class="kt">ssize_t</span><span class="o">&gt;</span> <span class="n">send</span><span class="p">(</span><span class="n">Code</span> <span class="n">code</span><span class="p">);</span></code></pre></figure>

<p>You can use this overload to send a response with an empty body and a given
HTTP Code (e.g <code>Http::Code::Ok</code>)</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Async</span><span class="o">::</span><span class="n">Promise</span><span class="o">&lt;</span><span class="kt">ssize_t</span><span class="o">&gt;</span> <span class="n">send</span><span class="p">(</span>
            <span class="n">Code</span> <span class="n">code</span><span class="p">,</span>
            <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&amp;</span> <span class="n">body</span><span class="p">,</span>
            <span class="k">const</span> <span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span> <span class="o">&amp;</span><span class="n">mime</span> <span class="o">=</span> <span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span><span class="p">());</span></code></pre></figure>

<p>This overload can be used to send a response with static, fixed-size content (body).
A MIME type can also be specified, which will be sent through the <code>Content-Type</code> header.</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">template</span><span class="o">&lt;</span><span class="kt">size_t</span> <span class="n">N</span><span class="o">&gt;</span>
<span class="n">Async</span><span class="o">::</span><span class="n">Promise</span><span class="o">&lt;</span><span class="kt">ssize_t</span><span class="o">&gt;</span> <span class="n">send</span><span class="p">(</span>
            <span class="n">Code</span> <span class="n">code</span><span class="p">,</span>
            <span class="k">const</span> <span class="kt">char</span> <span class="p">(</span><span class="o">&amp;</span><span class="n">arr</span><span class="p">)[</span><span class="n">N</span><span class="p">],</span>
            <span class="k">const</span> <span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span><span class="o">&amp;</span> <span class="n">mime</span> <span class="o">=</span> <span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span><span class="p">());</span></code></pre></figure>

<p>This version can also be used to send a fixed-size response with a body except that it
does not need to construct a string (no memory is allocated).
The size of the content is directly deduced by the compiler.
This version only works with raw string literals.</p>

<p>These functions are <code>asynchronous</code>, meaning that they do not return a plain old <code>ssize_t</code>
value indicating the number of bytes being sent, but instead a <code>Promise</code> that will be
fulfilled later on. See the next section for more details on asynchronous programming with
Pistache.</p>

<h2 id="response-streaming">Response streaming</h2>

<p>Sometimes, content that is to be sent back to the user can not be known in advance, thus the length
can not be determined in advance.
For that matter, the HTTP specification defines a special data-transfer mechanism called
<a href="http://tools.ietf.org/html/rfc7230#section-4.1">chunked encoding</a> where data is sent in a series
of <em>chunks</em>. This mechanism uses the <code>Transfer-Encoding</code> HTTP header in place of the <code>Content-Length</code> one.</p>

<p>To stream content, Pistache provides a special <code>ResponseStream</code> class. To get a ResponseStream from
a ResponseWriter, call the <code>stream()</code> member function:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">stream</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="n">stream</span><span class="p">(</span><span class="n">Http</span><span class="o">::</span><span class="n">Code</span><span class="o">::</span><span class="n">Ok</span><span class="p">);</span></code></pre></figure>

<p>To initate a stream, you have to pass the HTTP status code to the stream function (here <code>Http::Code::Ok</code> or <code>HTTP 200</code>).
The ResponseStream class provides an <code>iostream</code> like interface that overloads the <code>&lt;&lt;</code> operator.</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">stream</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;PO&quot;</span>
<span class="n">stream</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;NG&quot;</span></code></pre></figure>

<p>The first line will write a chunk of size 2 with the content PO to the stream’s buffer. The second line will write a second
chunk of size 2 with the content “NG”. To end the stream and flush the content, use the special <code>ends</code> marker:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">stream</span> <span class="o">&lt;&lt;</span> <span class="n">ends</span></code></pre></figure>

<p>The <code>ends</code> marker will write the last chunk of size 0 and send the final data over the network. To simply flush the stream’s buffer
without ending the stream, you can use the <code>flush</code> marker:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">stream</span> <span class="o">&lt;&lt;</span> <span class="n">flush</span></code></pre></figure>

<div class="note note-warning" role="note">
           <h4>Headers writing </h4>
           <p>
After starting a stream, headers become immutable. They must be written to the response before creating a ResponseStream:


<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">response</span><span class="p">.</span><span class="n">headers</span><span class="p">()</span>
    <span class="p">.</span><span class="n">add</span><span class="o">&lt;</span><span class="n">Header</span><span class="o">::</span><span class="n">Server</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;lys&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="n">add</span><span class="o">&lt;</span><span class="n">Header</span><span class="o">::</span><span class="n">ContentType</span><span class="o">&gt;</span><span class="p">(</span><span class="n">MIME</span><span class="p">(</span><span class="n">Text</span><span class="p">,</span> <span class="n">Plain</span><span class="p">));</span>

<span class="k">auto</span> <span class="n">stream</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="n">stream</span><span class="p">();</span>
<span class="n">stream</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;PO&quot;</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;NG&quot;</span> <span class="o">&lt;&lt;</span> <span class="n">ends</span><span class="p">;</span></code></pre></figure>

</p>
       </div>

<h2 id="static-file-serving">Static file serving</h2>

<p>In addition to text content serving, Pistache provides a way to serve static files through the <code>Http::serveFile</code> function:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">if</span> <span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">resource</span><span class="p">()</span> <span class="o">==</span> <span class="s">&quot;/doc&quot;</span> <span class="o">&amp;&amp;</span> <span class="n">request</span><span class="p">.</span><span class="n">method</span> <span class="o">==</span> <span class="n">Http</span><span class="o">::</span><span class="n">Method</span><span class="o">::</span><span class="n">Get</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">Http</span><span class="o">::</span><span class="n">serveFile</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s">&quot;README.md&quot;</span><span class="p">);</span>
<span class="p">}</span></code></pre></figure>

<div class="note note-info" role="note">
           <h4>Return value </h4>
           <p>
serveFile also returns a Promise representing the total number of bytes being sent to the wire
</p>
       </div>

<h2 id="controlling-timeout">Controlling timeout</h2>

<p>Sometimes, you might require to timeout after a certain amount of time. For example, if you are designing an HTTP API
with soft real-time constraints, you will have a time constraint to send a response back to the client.
That is why Pistache provides the ability to control the timeout on a per-request basis. To arm a timeout on a response,
you can use the <code>timeoufterAfter()</code> member function directly on the <code>ResponseWriter</code> object:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">response</span><span class="p">.</span><span class="n">timeoutAfter</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="p">(</span><span class="mi">500</span><span class="p">));</span></code></pre></figure>

<p>This will trigger a timeout if a response has not been sent within 500 milliseconds. <code>timeoutAfter</code> accepts any kind
of duration.</p>

<p>When a timeout triggers, the <code>onTimeout()</code> function from your handler will be called. By default, this method does nothing. If you
want to handle your timeout properly, you should then override this function inside your own handler:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="kt">void</span> <span class="nf">onTimeout</span><span class="p">(</span><span class="k">const</span> <span class="n">Http</span><span class="o">::</span><span class="n">Request</span><span class="o">&amp;</span> <span class="n">request</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">ResponseWriter</span> <span class="n">writer</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">request</span><span class="p">.</span><span class="n">send</span><span class="p">(</span><span class="n">Http</span><span class="o">::</span><span class="n">Code</span><span class="o">::</span><span class="n">No_Content</span><span class="p">);</span>
<span class="p">}</span></code></pre></figure>

<p>The <code>Request</code> object that is passed to the onTimeout is the exact same request that triggered the timeout. The <code>ResponseWriter</code> is a
complete new writer object.</p>

<div class="note note-info" role="note">
           <h4>ResponseWriter state </h4>
           <p>
Since the ResponseWriter object is a complete new object, state is not preserved with the ResponseWriter from the onRequest() callback,
which means that you will have to write the complete response again, including headers and cookies.
</p>
       </div>

<h1 id="asynchronous-http-programming">Asynchronous HTTP programming</h1>

<p>Interfaces provided by <code>Pistaches</code> are <code>asynchronous</code> and <code>non-blocking</code>. Asynchronous programming allows for code
to continue executing even if the result of a given call is not available yet. Calls that provide an asynchronous
interface are referred to <code>asynchronous calls</code>.</p>

<p>An example of such a call is the <code>send()</code> function provided by the <code>ResponseWriter</code> interface.
This function returns the number of bytes written to the socket file descriptor associated to the connection.
However, instead of returning directly the value to the caller and thus blocking the caller, it wraps
the value into a component called a <code>Promise</code>.</p>

<p>A <code>Promise</code> is the Pistache’s implementation of the
<a href="https://promisesaplus.com/">Promises/A+</a> standard available in many Javascript implementations. Simply put, during an
asynchronous call, a <code>Promise</code> separates the launch of an asynchronous operation from the retrieval of its result.
While the asynchronous might still be running, a <code>Promise&lt;T&gt;</code> is directly returned to the caller to retrieve the final
result when it becomes available. A so called <code>continuation</code> can be attach to a Promise to execute a callback when
the result becomes available (when the Promise has been resolved or fulfilled).</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">res</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="n">send</span><span class="p">(</span><span class="n">Http</span><span class="o">::</span><span class="n">Code</span><span class="o">::</span><span class="n">Ok</span><span class="p">,</span> <span class="s">&quot;Hello World&quot;</span><span class="p">);</span>
<span class="n">res</span><span class="p">.</span><span class="n">then</span><span class="p">(</span>
    <span class="p">[](</span><span class="kt">ssize_t</span> <span class="n">bytes</span><span class="p">)</span> <span class="p">{</span> <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">bytes</span> <span class="o">&lt;&lt;</span> <span class="s">&quot; bytes have been sent&quot;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span> <span class="p">},</span>
    <span class="n">Async</span><span class="o">::</span><span class="n">NoExcept</span>
<span class="p">);</span></code></pre></figure>

<p>The <code>then()</code> member is used to attach a callback to the Promise. The first argument is a <code>callable</code> that will be called
when the Promise has been <strong>succesfully</strong> resolved. If, for some reason, an error occurs during the asynchronous operation,
a Promise can be <strong>rejected</strong> and will then fail. In this case, the second callable will be called. <code>Async::NoExcept</code> is
a special callback that will call <code>std::terminate()</code> if the promise failed. This is the equivalent of the <code>noexcept</code> keyword.</p>

<p>Other generic callbacks can also be used in this case:</p>

<ul>
  <li><code>Async::IgnoreException</code> will simply ignore the exception and let the program continue</li>
  <li><code>Async::Throw</code> will “rethrow” the exception up to an eventual promise call-chain. This has the same effect than the <code>throw</code>
keyword, except that it is suitable for promises.</li>
</ul>

<p>Exceptions in promises callbacks are propagated through an <code>exception_ptr</code>.
Promises can also be chained together to create a whole asynchronous pipeline:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="lineno">1 </span><span class="k">auto</span> <span class="n">fetchOp</span> <span class="o">=</span> <span class="n">fetchDatabase</span><span class="p">();</span>
<span class="lineno">2 </span><span class="n">fetchOp</span>
<span class="lineno">3 </span> <span class="p">.</span><span class="n">then</span><span class="p">(</span>
<span class="lineno">4 </span>    <span class="p">[](</span><span class="k">const</span> <span class="n">User</span><span class="o">&amp;</span> <span class="n">user</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">fetchUserInfo</span><span class="p">(</span><span class="n">user</span><span class="p">);</span> <span class="p">},</span>
<span class="lineno">5 </span>    <span class="n">Async</span><span class="o">::</span><span class="n">Throw</span><span class="p">)</span>
<span class="lineno">6 </span> <span class="p">.</span><span class="n">then</span><span class="p">(</span>
<span class="lineno">7 </span>    <span class="p">[](</span><span class="k">const</span> <span class="n">UserInfo</span><span class="o">&amp;</span> <span class="n">info</span><span class="p">)</span> <span class="p">{</span> <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;User name = &quot;</span> <span class="o">&lt;&lt;</span> <span class="n">info</span><span class="p">.</span><span class="n">name</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span> <span class="p">},</span>
<span class="lineno">8 </span>    <span class="p">[](</span><span class="n">exception_ptr</span> <span class="n">ptr</span><span class="p">)</span> <span class="p">{</span> <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;An exception occured during user retrieval&quot;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="lineno">9 </span><span class="p">});</span></code></pre></figure>

<p>Line 5 will propagate the exception if <code>fetchDatabase()</code> failed and rejected the promise.</p>

<h1 id="headers">Headers</h1>

<h2 id="overview">Overview</h2>

<p>Inspired by the <a href="https://www.rust-lang.org/">Rust</a> eco-system and <a href="http://hyper.rs">Hyper</a>, HTTP headers are represented
as <code>type-safe</code> plain objects. Instead of representing headers as a pair of <code>(key: string, value: value)</code>, the choice has
been made to represent them as plain objects. This greatly reduces the risk of typo errors that can not catched by the
compiler with plain old strings.</p>

<p>Instead, objects give the compiler the ability to catch errors directly at compile-time,
as the user can not add or request a header through its name: it has to use the whole <strong>type</strong>. Types being enforced
at compile-time, it helps reducing common typo errors.</p>

<p>With <code>Pistache</code>, each HTTP Header is a <code>class</code> that inherits from the <code>Http::Header</code> base class and use the <code>NAME()</code> macro
to define the name of the header. List of all headers inside an HTTP request or response are stored inside an internal
<code>std::unordered_map</code>, wrapped in an <code>Header::Collection</code> class. Invidual headers can be retrieved or added to this object
through the whole type of the header:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">headers</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="n">headers</span><span class="p">();</span>
<span class="k">auto</span> <span class="n">ct</span> <span class="o">=</span> <span class="n">headers</span><span class="p">.</span><span class="n">get</span><span class="o">&lt;</span><span class="n">Http</span><span class="o">::</span><span class="n">Header</span><span class="o">::</span><span class="n">ContentType</span><span class="o">&gt;</span><span class="p">();</span></code></pre></figure>

<p><code>get&lt;H&gt;</code> will return a <code>std::shared_ptr&lt;H&gt;</code> where <code>H: Header</code> (H inherits from Header). If the header does not exist, <code>get&lt;H&gt;</code>
will throw an exception. <code>tryGet&lt;H&gt;</code> provides a non-throwing alternative that, instead, returns a null pointer.</p>

<div class="note note-info" role="note">
           <h4>Built-in headers </h4>
           <p>
Headers provided by Pistache live in the Http::Header namespace
</p>
       </div>

<h2 id="defining-your-own-header">Defining your own header</h2>

<p>Common headers defined by the HTTP RFC (<a href="https://pretty-rfc.herokuapp.com/RFC2616">RFC2616</a>) are already implemented and available.
However, some APIs might define extra headers that do not exist in <code>Pistache</code>. To support your own header types, you can define
and register your own HTTP Header by first declaring a class that inherits the <code>Http::Header</code> class:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">class</span> <span class="nc">XProtocolVersion</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Http</span><span class="o">::</span><span class="n">Header</span> <span class="p">{</span>
<span class="p">};</span></code></pre></figure>

<p>Since every header has a name, the <code>NAME()</code> macro must be used to name the header properly:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">class</span> <span class="nc">XProtocolVersion</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Http</span><span class="o">::</span><span class="n">Header</span> <span class="p">{</span>
    <span class="n">NAME</span><span class="p">(</span><span class="s">&quot;X-Protocol-Version&quot;</span><span class="p">)</span>
<span class="p">};</span></code></pre></figure>

<p>The <code>Http::Header</code> base class provides two virtual methods that you must override in your own implementation:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"> <span class="kt">void</span> <span class="nf">parse</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&amp;</span> <span class="n">data</span><span class="p">);</span> </code></pre></figure>

<p>This function is used to parse the header from the string representation. Alternatively, to avoid allocating memory for the string representation,
a <em>raw</em> version can be used:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="kt">void</span> <span class="nf">parseRaw</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span><span class="o">*</span> <span class="n">str</span><span class="p">,</span> <span class="kt">size_t</span> <span class="n">len</span><span class="p">);</span></code></pre></figure>

<p><code>str</code> will directly point to the header buffer from the raw http stream. The <code>len</code> parameter is the total length of the header’s value.</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"> <span class="kt">void</span> <span class="n">write</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&amp;</span> <span class="n">stream</span><span class="p">)</span> <span class="k">const</span> </code></pre></figure>

<p>When writing the response back to the client, the <code>write</code> function is used to serialize the header into the network buffer.</p>

<p>Let’s combine these functions together to finalize the implementation of our previously declared header:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">class</span> <span class="nc">XProtocolVersion</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Http</span><span class="o">::</span><span class="n">Header</span> <span class="p">{</span>
<span class="k">public</span><span class="o">:</span>

    <span class="n">NAME</span><span class="p">(</span><span class="s">&quot;X-Protocol-Version&quot;</span><span class="p">)</span>

    <span class="n">XProtocolVersion</span><span class="p">()</span>
     <span class="o">:</span> <span class="n">minor</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
     <span class="p">,</span> <span class="n">major</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
    <span class="p">{</span> <span class="p">}</span>

    <span class="kt">void</span> <span class="n">parse</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&amp;</span> <span class="n">data</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">auto</span> <span class="n">pos</span> <span class="o">=</span> <span class="n">data</span><span class="p">.</span><span class="n">find</span><span class="p">(</span><span class="sc">&#39;.&#39;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">pos</span> <span class="o">!=</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">::</span><span class="n">npos</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">minor</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">stoi</span><span class="p">(</span><span class="n">data</span><span class="p">.</span><span class="n">substr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">pos</span><span class="p">));</span>
            <span class="n">major</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">stoi</span><span class="p">(</span><span class="n">data</span><span class="p">.</span><span class="n">substr</span><span class="p">(</span><span class="n">pos</span> <span class="o">+</span> <span class="mi">1</span><span class="p">));</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="kt">void</span> <span class="n">write</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&amp;</span> <span class="n">os</span><span class="p">)</span> <span class="k">const</span> <span class="p">{</span>
        <span class="n">os</span> <span class="o">&lt;&lt;</span> <span class="n">minor</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;.&quot;</span> <span class="o">&lt;&lt;</span> <span class="n">major</span><span class="p">;</span>
    <span class="p">}</span>
<span class="k">private</span><span class="o">:</span>
    <span class="kt">int</span> <span class="n">minor</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">major</span><span class="p">;</span>
<span class="p">};</span></code></pre></figure>

<p>And that’s it. Now all we have to do is registering the header to the registry system:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Header</span><span class="o">::</span><span class="n">Registry</span><span class="o">::</span><span class="n">registerHeader</span><span class="o">&lt;</span><span class="n">XProtocolVersion</span><span class="o">&gt;</span><span class="p">();</span></code></pre></figure>

<div class="note note-info" role="note">
           <h4>Header's instantation </h4>
           <p>
You should always provide a default constructor for your header so that it can be instantiated by the registry system
</p>
       </div>

<p>Now, the <code>XProtocolVersion</code> can be retrieved and added like any other header in the <code>Header::Collection</code> class.</p>

<div class="note note-info" role="note">
           <h4>Unknown headers </h4>
           <p>
Headers that are not known to the registry system are stored as a raw pair of strings in the Collection class.

getRaw() can be used to retrieve a raw header:


<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">myHeader</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="n">headers</span><span class="p">().</span><span class="n">getRaw</span><span class="p">(</span><span class="s">&quot;x-raw-header&quot;</span><span class="p">);</span>
<span class="n">myHeader</span><span class="p">.</span><span class="n">name</span><span class="p">()</span> <span class="c1">// x-raw-header</span>
<span class="n">myHeader</span><span class="p">.</span><span class="n">value</span><span class="p">()</span> <span class="c1">// returns the value of the header as a string</span></code></pre></figure>

</p>
       </div>

<h2 id="mime-types">MIME types</h2>

<p><a href="https://en.wikipedia.org/wiki/Media_type">MIME Types</a> (or Media Type) are also fully typed. Such types are for example
used in an HTTP request or response to describe the data contained in the body of the message (<code>Content-Type</code> header, …)
and are composed of a <em>type</em>, <em>subtype</em>, and optional <em>suffix</em> and parameters.</p>

<p>MIME Types are represented by the <code>Mime::MediaType</code> class, implemented in the <code>mime.h</code> header. A MIME type can be directly
constructed from a string:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">mime</span> <span class="o">=</span> <span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span><span class="o">::</span><span class="n">fromString</span><span class="p">(</span><span class="s">&quot;application/json&quot;</span><span class="p">);</span></code></pre></figure>

<p>However, to enforce type-safety, common types are all represented as enumerations:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span> <span class="n">m1</span><span class="p">(</span><span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">Type</span><span class="o">::</span><span class="n">Application</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">Subtype</span><span class="o">::</span><span class="n">Json</span><span class="p">);</span></code></pre></figure>

<p>To avoid such a typing pain, a <code>MIME</code> macro is also provided:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">m1</span> <span class="o">=</span> <span class="n">MIME</span><span class="p">(</span><span class="n">Application</span><span class="p">,</span> <span class="n">Json</span><span class="p">);</span></code></pre></figure>

<p>For suffix MIMEs, use the special <code>MIME3</code> macro:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">m1</span> <span class="o">=</span> <span class="n">MIME3</span><span class="p">(</span><span class="n">Application</span><span class="p">,</span> <span class="n">Json</span><span class="p">,</span> <span class="n">Zip</span><span class="p">);</span></code></pre></figure>

<p>If you like typing, you can also use the long form:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">MediaType</span> <span class="n">m1</span><span class="p">(</span><span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">Type</span><span class="o">::</span><span class="n">Application</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">Subtype</span><span class="o">::</span><span class="n">Json</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">Mime</span><span class="o">::</span><span class="n">Suffix</span><span class="o">::</span><span class="n">Zip</span><span class="p">);</span></code></pre></figure>

<p>The <code>toString()</code> function can be used to get the string representation of a given MIME type:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">auto</span> <span class="n">m1</span> <span class="o">=</span> <span class="n">MIME</span><span class="p">(</span><span class="n">Text</span><span class="p">,</span> <span class="n">Html</span><span class="p">);</span>
<span class="n">m1</span><span class="p">.</span><span class="n">toString</span><span class="p">();</span> <span class="c1">// text/html</span></code></pre></figure>

<h1 id="routing">Routing</h1>

<p>HTTP routing consists of binding an HTTP route to a C++ callback. A special component called an HTTP router will
be in charge of dispatching HTTP requests to the right C++ callback.
A route is composed of an HTTP verb associated to a resource:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">GET</span> <span class="o">/</span><span class="n">users</span><span class="o">/</span><span class="mi">1</span></code></pre></figure>

<p>Here, <code>GET</code> is the verb and <code>/users/1</code> is the associated resource.</p>

<h2 id="http-methods">HTTP methods</h2>

<p>A bunch of HTTP methods (verbs) are supported by Pistache:</p>

<ul>
  <li><em>GET</em>: The <code>GET</code> method is used by the client (e.g <code>browser</code>) to retrieve a ressource identified by an URI.
For example, to retrieve an user identified by an id, a client will issue a <code>GET</code> to the <code>/users/:id</code> Request-URI.</li>
  <li><em>POST</em>: the <code>POST</code> method is used to post or send new information to a certain ressource. The server will then read
and store the data associated to the request. POST is a common way of transmitting data from an HTML form. POST can
also be used to create a new resource or update information of an existing resource. For example, to create a new
user, a client will issue a <code>POST</code> to the <code>/users</code>  path with the data of the user to create in its body.</li>
  <li><em>PUT</em>: <code>PUT</code> is very similar to <code>POST</code> except that <code>PUT</code> is idempotent, meaning that two requests to the same Request-URI
with the same identical content should have the same effect and should produce the same result.</li>
  <li><em>DELETE</em>: the <code>DELETE</code> method is used to delete a resource associated to a given Request-URI. For example, to remove
an user, a client might issue a <code>DELETE</code> call to the <code>/users/:id</code> Request-URI.</li>
</ul>

<p>To sum up, <code>POST</code> and <code>PUT</code> are used to Create and/or Update, <code>GET</code> is used to Read and <code>DELETE</code> is used to Delete
information.</p>

<h2 id="route-patterns">Route patterns</h2>

<h3 id="static-routes">Static routes</h3>

<p>Static routes are the simplest ones as they do rely on dynamic parts of the Request-URI.
For example <code>/users/all</code> is a static route that will exactly match the <code>/users/all</code> Request-URI.</p>

<h3 id="dynamic-routes">Dynamic routes</h3>

<p>However, it is often useful to define routes that have dynamic parts. For example, to retrieve a specific user
by its id, the id is needed to query the storage. Dynamic routes thus have parameters that are then matched
one by one by the HTTP router. In a dynamic route, parameters are identified by a column <code>:</code></p>

<p><code>/users/:id</code></p>

<p>Here, <code>:id</code> is a dynamic parameter. When a request comes in, the router will try to match the <code>:id</code> parameter to
the corresponding part of the request. For example, if the server receives a request to <code>/users/13</code>, the router will
match the <code>13</code> value to the <code>:id</code> parameter.</p>

<p>Some parameters, like <code>:id</code> are named. However, <code>Pistache</code> also allows <em>splat</em> (wildcard) parameters, identified by a star <code>*</code>:</p>

<p><code>/link/*/to/*</code></p>

<h2 id="defining-routes">Defining routes</h2>

<p>To define your routes, you first have to instantiate an HTTP router:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Http</span><span class="o">::</span><span class="n">Router</span> <span class="n">router</span></code></pre></figure>

<p>Then, use the <code>Routes::&lt;Method&gt;()</code> functions to add some routes:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">Routes</span><span class="o">::</span><span class="n">Get</span><span class="p">(</span><span class="n">router</span><span class="p">,</span> <span class="s">&quot;/users/all&quot;</span><span class="p">,</span> <span class="n">Routes</span><span class="o">::</span><span class="n">bind</span><span class="p">(</span><span class="o">&amp;</span><span class="n">UsersApi</span><span class="o">::</span><span class="n">getAllUsers</span><span class="p">,</span> <span class="k">this</span><span class="p">));</span>
<span class="n">Routes</span><span class="o">::</span><span class="n">Post</span><span class="p">(</span><span class="n">router</span><span class="p">,</span> <span class="s">&quot;/users/:id&quot;</span><span class="p">,</span> <span class="n">Routes</span><span class="o">::</span><span class="n">bind</span><span class="p">(</span><span class="o">&amp;</span><span class="n">UsersApi</span><span class="o">::</span><span class="n">getUserId</span><span class="p">,</span> <span class="k">this</span><span class="p">));</span>
<span class="n">Routes</span><span class="o">::</span><span class="n">Get</span><span class="p">(</span><span class="n">router</span><span class="p">,</span> <span class="s">&quot;/link/*/to/*&quot;</span><span class="p">,</span> <span class="n">Routes</span><span class="o">::</span><span class="n">bind</span><span class="p">(</span><span class="o">&amp;</span><span class="n">UsersApi</span><span class="o">::</span><span class="n">linkUsers</span><span class="p">,</span> <span class="k">this</span><span class="p">));</span></code></pre></figure>

<p><code>Routes::bind</code> is a special function that will generate a corresponding C++ callback that will then
be called by the router if a given route matches the Request-URI.</p>

<h3 id="callbacks">Callbacks</h3>

<p>A C++ callback associated to a route must have the following signature:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="kt">void</span><span class="p">(</span><span class="k">const</span> <span class="n">Rest</span><span class="o">::</span><span class="n">Request</span><span class="o">&amp;</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">ResponseWriter</span><span class="p">);</span></code></pre></figure>

<p>A callback can either be a non-static free or member function. For member functions, a pointer to the
corresponding instance must be passed to the <code>Routes::bind</code> function so that the router knows on which
instance to invoke the member function.</p>

<p>The first parameter of the callback is <code>Rest::Request</code> and not an <code>Http::Request</code>. A <code>Rest::Request</code> is
an <code>Http::Request</code> will additional functions. Named and splat parameters are for example retrieved through
this object:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="kt">void</span> <span class="n">UsersApi</span><span class="o">::</span><span class="n">getUserId</span><span class="p">(</span><span class="k">const</span> <span class="n">Rest</span><span class="o">::</span><span class="n">Request</span><span class="o">&amp;</span> <span class="n">request</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">ResponseWriter</span> <span class="n">response</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">auto</span> <span class="n">id</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="n">param</span><span class="p">(</span><span class="s">&quot;:id&quot;</span><span class="p">).</span><span class="n">as</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="p">();</span>
    <span class="c1">// ...</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="n">UsersApi</span><span class="o">::</span><span class="n">linkUsers</span><span class="p">(</span><span class="k">const</span> <span class="n">Rest</span><span class="o">::</span><span class="n">Request</span><span class="o">&amp;</span> <span class="n">request</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">ResponseWriter</span> <span class="n">response</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">auto</span> <span class="n">u1</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="n">splatAt</span><span class="p">(</span><span class="mi">0</span><span class="p">).</span><span class="n">as</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span><span class="p">();</span>
    <span class="k">auto</span> <span class="n">u2</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="n">splatAt</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="n">as</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span><span class="p">();</span>
    <span class="c1">// ...</span>
<span class="p">}</span></code></pre></figure>

<p>As you can see, parameters are also typed. To cast a parameter to the appropriate type, use the <code>as&lt;T&gt;</code> member template.</p>

<div class="note note-info" role="note">
           <h4>Cast safety </h4>
           <p>
An exception will be thrown if the parameter can not be casted to the right type
</p>
       </div>

<h2 id="installing-the-handler">Installing the handler</h2>

<p>Once the routes have been defined, the final <code>Http::Handler</code> must be set to the HTTP Endpoint. To retrieve the handler,
just call the <code>handler()</code> member function on the router object:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">endpoint</span><span class="p">.</span><span class="n">setHandler</span><span class="p">(</span><span class="n">router</span><span class="p">.</span><span class="n">handler</span><span class="p">());</span></code></pre></figure>

<h1 id="rest-description">REST description</h1>

<p>Documentation writing for this part is still in progress, please refer to the
<a href="https://github.com/oktal/pistache/blob/master/examples/rest_description.cc">rest_description</a> example</p>

<h2 id="swagger">Swagger</h2>

<h1 id="api-reference">API Reference</h1>


		</div>
	</div>
</div>
        <footer class="main-footer">
            <div class="wc-container">
                <div class="column one">
                    <h6>Few more links</h6>
<ul class="menu">
</ul>		
                    
                </div>
                <div class="column two">
                    <h6>Follow me</h6>

<ul class="social-media">


    

    
    <li>
        <a title="oktal on Github" 
            href="https://github.com/oktal" 
            class="github wc-img-replace" target="_blank">Github</a>
    </li>
     

    

    

    

    

</ul>
                </div>
            </div>
            <p class="wc-container disclaimer">
                
Powered by <a href="http://jekyllrb.com" target="_blank">Jekyll</a>
            </p>
        </footer>
        <script type="text/javascript">
          /* To avoid render blocking css */
          var cb = function() {
            var l = document.createElement('link'); l.rel = 'stylesheet';
            l.href = 'http://fonts.googleapis.com/css?family=Ubuntu+Mono&subset=latin';
            var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
          };
          var raf = requestAnimationFrame || mozRequestAnimationFrame ||
              webkitRequestAnimationFrame || msRequestAnimationFrame;
          if (raf) raf(cb);
          else window.addEventListener('load', cb);
        </script>
        <!-- jQuery -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <!-- When no internet load JQuery from local -->
        <script>window.jQuery || document.write('<script src="/assets/js/jquery.min.js"><\/script>')</script>
        <!-- Site js -->
        <script src="/assets/js/all.js"></script>
        <!-- Google analytics  -->
        
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-xxxx-x']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

    </body>        
</html>
